﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using System.ComponentModel;

namespace Lib.Web.Mvc.Unity
{
    public class UnityModelBinderProvider : IModelBinderProvider
    {
        #region Fields
        private IUnityContainer _container;
        #endregion

        #region Constructor
        public UnityModelBinderProvider(IUnityContainer container)
        {
            _container = container;
        }
        #endregion

        #region IModelBinderProvider Members
        public IModelBinder GetBinder(Type modelType)
        {
            AttributeCollection allAttributes = TypeDescriptor.GetAttributes(modelType);
            if (allAttributes != null)
            {
                ModelBinderAttribute[] modelBinderAttributes = allAttributes.OfType<ModelBinderAttribute>().ToArray();
                if (modelBinderAttributes != null && modelBinderAttributes.Length == 1)
                {
                    try
                    {
                        return _container.Resolve(modelBinderAttributes[0].BinderType) as IModelBinder;
                    }
                    catch
                    {
                        return null;
                    }
                }
            }

            return null;
        }
        #endregion
    }
}
